import { ref, watch } from 'vue'
import { defineStore } from 'pinia'
import { getGoodsAPI ,getCategoryAPI,getProdInfoAPI} from '@/apis/home.js'
import {spuEvaluationAPI} from "@/apis/order"
export const useshopProduct = defineStore('product', () => {
	
	const goodsProduct = ref([])
	//商品总数
	let totalNum=ref(0)
	//每页数量
	let pageSize=ref(20)
	//总页数
	let totalPages=ref(0)
	//搜索字段
	let pageKeyWord=ref("")
	//当前页
	let pageNum=ref(1)
	//排序条件：1新品,2销量倒序,3销量正序,4商品价格倒序,5商品价格正序,6评论(暂无评论)
	let sortType=ref(2)
	//商品分类
	let shopCategory=ref([])
	//当前分类标识
		//一级分类
		let shopPrimaryCategoryId=ref(-1)
		//二级分类
		let shopSecondaryCategoryId=ref(-1)
	//价格范围
	let shopPriceList=ref([
		{
			minPrice:0.,
			maxPrice:100,
			name:"0-100"
		},
		{
			minPrice:101.,
			maxPrice:500,
			name:"100-500"
		},
		{
			minPrice:501.,
			maxPrice:1000,
			name:"500-1000"
		},
		{
			minPrice:1000,
			maxPrice:"",
			name:"1000以上"
		}
	])
	//当前价格区间
	let shopPrice=ref(-1)
	//监听翻页与筛选条件改变事件
	watch([pageNum],()=>{
		getShopData()
	})
	watch([shopPrimaryCategoryId,shopSecondaryCategoryId,shopPrice,sortType],()=>{
		if(pageNum.value!==1){
			pageNum.value=1
		}else{
			getShopData()
		}
	})
	//获取数据（在此传入筛选条件）
	const getShopData=async ()=>{
			let formData={
				sort:sortType.value,
				keyword:pageKeyWord.value,
				pageNum:pageNum.value,
				pageSize:pageSize.value,
				shopPrimaryCategoryId:shopPrimaryCategoryId.value>-1?shopCategory.value[shopPrimaryCategoryId.value].categoryId:"",
				shopSecondaryCategoryId:shopSecondaryCategoryId.value>-1?shopCategory.value[shopPrimaryCategoryId.value].categories[shopSecondaryCategoryId.value].categoryId:"",
				minPrice:shopPrice.value>-1?shopPriceList.value[shopPrice.value].minPrice:'',
				maxPrice:shopPrice.value>-1?shopPriceList.value[shopPrice.value].maxPrice:'',
				//暂时没有低于1000的商品，调整数据后使用
				// maxPrice:shopPriceList.value[shopPrice.value].maxPrice
			}
			const res = await getGoodsAPI(formData)
			let {code,msg,data:{list,total,pages}}=res
			if(code=='00000'){
				goodsProduct.value = list[0].spus
				totalPages.value=pages
				totalNum.value=total
			}
	}
	
	//获取全部分类
	const getShopCategory=async()=>{
		let res=await getCategoryAPI({shopId:0})
		let {data}=res
		shopCategory.value=data
		getShopData()
	}
	//获取商品详情
	const getProdInfo=async(spuId)=>{
		let res=await getProdInfoAPI({
			spuId:spuId
		})
		return res
	}
	//用户评论
	const userEvaluation=async (data)=>{
		let res=await spuEvaluationAPI(data)
		return res
	}
  return {
	goodsProduct,
	totalNum,
	totalPages,
	pageNum,
	pageSize,
	pageKeyWord,
	sortType,
	shopCategory,
	shopPrimaryCategoryId,
	shopSecondaryCategoryId,
	shopPriceList,
	shopPrice,
	getShopData,
	getShopCategory,
	getProdInfo,
	userEvaluation,
  }
})